<template>
    <view class="container">
        <!-- 顶部固定区域 -->
        <view class="fixed-content">
            <!-- 顶部用户信息区域 -->
            <view class="user-info-box">
                <view class="user-avatar-section">
                    <image class="avatar"  @click="goUserLogin()" :src="userStore.userNextInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
                    <text class="text-primary" v-if="userStore.userNextInfo.name">{{userStore.userNextInfo.name}}</text>
                    <text class="text-primary" v-else>欢迎使用智慧药箱</text>
                </view>
                <view class="auth-box">
                    <text class="text-secondary">亲情授权</text>
                    <uni-icons type="right" size="16" color="#999"></uni-icons>
                </view>
            </view>

            <!-- 功能按钮区域 -->
            <view class="function-box">
                <view class="function-item">
                    <view class="function-icon">
                        <uni-icons type="list" size="24" color="#2ac2d1"></uni-icons>
                    </view>
                    <text class="text-primary">药品列表</text>
                </view>
                <view class="function-item">
                    <view class="function-icon">
                        <uni-icons type="star" @click="goToDrugGroup()" size="24" color="#2ac2d1"></uni-icons>
                    </view>
                    <text class="text-primary">药品组合</text>
                </view>
                <view class="function-item">
                    <view class="function-icon">
                        <uni-icons type="notification" @click="goToDrugReminder()" size="24" color="#2ac2d1"></uni-icons>
                    </view>
                    <text class="text-primary">用药提醒</text>
                </view>
            </view>
        </view>

        <text v-if="!userStore.isLogin" style="display: block; text-align: center; margin-top: 40rpx;">登录后可查看药品</text>
        <!-- 可滚动的内容区域 -->
        <scroll-view
            class="scrollable-content"
            scroll-y
            refresher-enabled
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh"
            @scrolltolower="handleScrollToLower"
            :lower-threshold="100"
            v-else
        >
            <!-- 药品列表区域 -->
            <view class="medicine-list">
                <!-- 使用v-for循环渲染药品列表 -->
                <uni-swipe-action>
                    <uni-swipe-action-item
                      v-for="(medicine, index) in medicineStore.medicines"
                      :key="index"
                      @click="handleDelete(medicine.id)"
                      :right-options="[
                          {
                              text: '删除',
                              style: {
                                  backgroundColor: '#dd524d'
                              },
                          }
                      ]"
                    >
                        <view class="medicine-item">
                            <view class="medicine-info">
                                <image class="medicine-image" :src="medicine.picture" mode="aspectFit"></image>
                                <view class="medicine-name">{{ medicine.drugName }}</view>
                            </view>
                            <view class="medicine-actions">
                                <button class="action-btn" size="mini" plain @click="handleAddToGroup(medicine.id, medicine.drugName)" v-if="isMedicineExpired(medicine.uselessTime)">添加到药品组合</button>
                                <button class="action-btn" style="background-color: white; color: red; border: 1px solid red;" v-else>已过期</button>
                                <button class="action-btn" size="mini" @click="goToDetail(medicine.id)" plain>详情</button>
                            </view>
                        </view>
                    </uni-swipe-action-item>
                </uni-swipe-action>
                <view class="no-more">
                    <view class="no-more-text">下拉可刷新数据</view>
                </view>
            </view>
        </scroll-view>

        <!-- 右下角添加按钮 -->
        <view class="float-icon" @click="navigateToEdit">
            <uni-icons type="plusempty" size="24" color="#2ac2d1"></uni-icons>
            <view class="add-count" v-if="addedMedicineCount > 0">{{ addedMedicineCount }}</view>
        </view>
    </view>
</template>

<script>
import { useMedicineStore } from '@/store/medicine';
import { useUserStore } from '../../store/user';

export default {
    setup() {
        const medicineStore = useMedicineStore();
        const userStore = useUserStore()
        return {
            medicineStore,
            userStore
        };
    },
    onLoad() {
      if(!this.userStore.isLogin){
        uni.showModal({
            title: '请先登录',
            content: '登录后可使用小程序',
            showCancel: false, // 设置不显示取消按钮
            success: function (res) {
                if (res.confirm) {
                    // 用户点击确定后执行跳转操作
                    uni.navigateTo({
                        url: '/pages/auth/auth'
                    });
                }
            }
        });
      }
    },
    data() {
        return {
            count: 0, // 记录点击数量
            medicineList: [] ,// 记录选中的药品，
            addedMedicineCount: 0,
            addedMedicines: [],
            isRefreshing: false,
        };
    },
    methods: {
      // 判断药品是否过期
      isMedicineExpired(medicine) {
          // 获取当前时间的时间戳
          const currentTime = new Date().getTime();
          // 尝试将 medicine.uselessTime 转换为 iOS 支持的格式
          let formattedUselessTime = medicine;
          if (formattedUselessTime.includes('-')) {
              formattedUselessTime = formattedUselessTime.replace(/-/g, '/');
          }
          // 获取 medicine.uselessTime 的时间戳
          const uselessTime = new Date(formattedUselessTime).getTime();
          // 判断是否过期
          return currentTime < uselessTime;
      },
      handleScrollToLower() {
          if (this.medicineStore.page * this.medicineStore.pageSize >= this.medicineStore.total) {
              this.medicineStore.hasMore = false;
              return;
          }
          this.medicineStore.page++;
          this.medicineStore.getMedicineList()
      },
      
      async onRefresh() {
          this.isRefreshing = true;
          this.medicineStore.page = 1;
          this.medicineStore.hasMore = true;
          try {
              await this.medicineStore.getMedicineList() // 重新加载数据
              uni.showToast({
                  title: '刷新成功',
                  icon: 'success',
              });
          } catch (error) {
              uni.showToast({
                  title: '刷新失败',
                  icon: 'error',
              });
          } finally {
              this.isRefreshing = false;
          }
      },
      
        goUserLogin(){
            uni.navigateTo({
                url:'/pages/auth/auth'
            })
        },
        goToDetail(id){
            console.log(id);
            uni.navigateTo({
                url:`/subpkgDetail/drugDetail/drugDetail?id=${id}`
            })
        },
        navigateToEdit() {
            // 检查 addedMedicines 数组的长度
            if (this.addedMedicines.length < 2) {
              // 如果数组长度小于 2，显示提示框
              uni.showToast({
                title: '药品数量少于两个',
                icon: 'none'
              });
              return; // 阻止后续代码执行，不进行跳转
            }
        
            // 如果数组长度大于等于 2，执行跳转操作
            uni.navigateTo({
              url: '/pages/group/edit?addedMedicines=' + encodeURIComponent(JSON.stringify(this.addedMedicines)),
            });
            this.addedMedicineCount = 0;
            this.addedMedicines = []; // 清空数组
        },
        handleAddToGroup(id, name) {
            const isAlreadyAdded = this.addedMedicines.some(item => item.id === id);
            if (!isAlreadyAdded) {
                this.addedMedicines.push({ id, name }); // 将药品 id 和 name 添加到数组中
                this.addedMedicineCount++; // 增加计数
                uni.showToast({
                    title: '已添加到组合',
                    icon: 'success',
                });
            } else {
                uni.showToast({
                    title: '该药品已添加',
                    icon: 'none',
                });
            }
        },
        goToDrugReminder(){
            uni.navigateTo({
                url:'/pages/reminder/reminder'
            })
        },
        goToDrugGroup(){
            uni.navigateTo({
                url:'/pages/group/group'
            })
        },
        // 新增删除事件处理函数
        async handleDelete(id) {
            try {
                // 调用删除药品的 API 或 store 方法
                await this.medicineStore.deleteMedicine(id);
                uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                });
            } catch (error) {
                console.error('删除药品失败:', error);
                uni.showToast({
                    title: '删除失败',
                    icon: 'none'
                });
            }
        },
        addToGroup(medicine) {
            this.count++;
            if (!this.medicineList.some(item => item.id === medicine.id)) {
                this.medicineList.push(medicine);
            }
        }
    }
};
</script>

<style lang="scss">
.container {
    height: 100vh;
    background-color: #f5f5f5;
    position: relative;
    display: flex;
    flex-direction: column;
}

.fixed-content {
    background-color: #ffffff;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.user-info-box {
    padding: 30rpx 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .user-avatar-section {
        display: flex;
        align-items: center;
        
        .avatar {
            width: 100rpx;
            height: 100rpx;
            border-radius: 50%;
            background-color: #f0f0f0;
            margin-right: 20rpx;
        }
    }
    
    .auth-box {
        display: flex;
        align-items: center;
        padding: 10rpx 20rpx;
        background-color: #f8f8f8;
        border-radius: 30rpx;
    }
}

.function-box {
    padding: 30rpx 20rpx;
    display: flex;
    justify-content: space-around;
    
    .function-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .function-icon {
            width: 80rpx;
            height: 80rpx;
            background-color: rgba(42, 194, 209, 0.1);
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 10rpx;
        }
    }
}

.scrollable-content {
    flex: 1;
    height: 0;
    padding-bottom: 20rpx;
}

.medicine-list {
    padding: 20rpx 20rpx 0;
    
    .medicine-item {
        background-color: #ffffff;
        padding: 20rpx;
        margin-bottom: 20rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 12rpx;
        
        .medicine-info {
            display: flex;
            align-items: center;
            
            .medicine-image {
                width: 80rpx;
                height: 80rpx;
                margin-right: 20rpx;
            }
            
            .medicine-name {
                font-size: 28rpx;
                color: #333;
            }
        }
        
        .medicine-actions {
            display: flex;
            gap: 10rpx;
            
            .action-btn {
                font-size: 24rpx;
                color: #2ac2d1;
                border-color: #2ac2d1;
                
                &::after {
                    border-color: #2ac2d1;
                }
            }
        }
    }
    
    .loading-more, .no-more {
        text-align: center;
        padding: 10rpx 0;
        
        .loading-text, .no-more-text {
            font-size: 24rpx;
            color: #999;
        }
    }
    
    .no-more {
        .no-more-text {
            color: #ccc;
        }
    }
}

.float-icon {
	position: fixed;
	right: 30rpx;
	bottom: 40rpx;
	width: 80rpx;
	height: 80rpx;
	background-color: #ffffff;
	border-radius: 50%;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 100;
}

.float-icon {
	position: fixed;
	right: 30rpx;
	bottom: 40rpx;
	width: 80rpx;
	height: 80rpx;
	background-color: #ffffff;
	border-radius: 50%;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 100;
	
	.add-count {
		position: absolute;
		top: 0;
		right: 0;
		background-color: #93e0e7;
		color: #ffffff;
		font-size: 20rpx;
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>